const puppeteer = require('puppeteer');  // 引入 puppeteer

// 封装异步定时器函数
const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time);
})

const url = 'https://movie.douban.com/tag/#/';  // 要爬取的网站地址
(async () => {
  const browser = await puppeteer.launch();  // 启动浏览器
  const page = await browser.newPage();  // 打开页面
  await page.goto(url);  // 地址栏输入网页地址

  await page.waitForSelector('.more');  // 等待页面准备好
  
  for (let i = 0; i < 2; i++) {
      await sleep(3000);  // 延迟 3 秒
      // 点击加载更多
      await page.click('.more')
  }

  const result = await page.evaluate(() => {
    const domList = document.querySelectorAll('.list-wp .item');

    if (domList.length > 0) {
      return Array.from(domList).map((item) => {
        const doubanId = item.querySelector('.cover-wp').dataset['id'];
        const oImg = item.querySelector('.pic img');
        const rate = item.querySelector('.rate').innerHTML;
        return {
          doubanId,
          detailUrl: item.href,
          poster: oImg.src,
          desc: oImg.alt,
          title: oImg.alt,
          rate
        }
      });
    }
  });

  await browser.close();  // 关闭浏览器
  // console.log(result)

  process.send({ result });  // 向子进程传递数据
  process.exit(0);  // 结束子进程并传递状态码
})();

